const axios = require("axios");
/**
 * axios拦截器封装
 */
class Request {
  constructor(requestConfig) {
    this.instance = axios.create(requestConfig);
    this.customInterceptors = requestConfig.interceptors;

    // 注册全局请求拦截
    this.instance.interceptors.request.use(
      (config) => {
        // 如果没指定请求数据类型，默认 json
        if (!config.headers["Content-Type"]) {
          config.headers["Content-Type"] = "application/json;charset=UTF-8";
        }
        return config;
      },
      (err) => err
    );

    // 注册全局响应拦截
    this.instance.interceptors.response.use(
      (res) => {
        const result = res.data;
        if (result) {
          if (result.isError) {
            return Promise.reject(result || { message: "请求出错!" });
          } else {
            // 正常返回数据
            return result.data;
          }
        }
        return Promise.reject(result || { message: "请求出错，请稍候再试" });
      },
      (err) => {
        const { response } = err;
        if (response) {
          errorHandle(response.status, response.data);
          return Promise.reject(response);
        }
        if (!err.message) {
          err.message = "请求出错，请稍候再试";
        }
        throw err;
      }
    );

    // 使用实例拦截器
    this.instance.interceptors.request.use(
      this.customInterceptors?.request,
      this.customInterceptors?.requestCatch
    );
    this.instance.interceptors.response.use(
      this.customInterceptors?.response,
      this.customInterceptors?.responseCatch
    );
  }

  request(config) {
    return new Promise((resolve, reject) => {
      // 单个请求的拦截器
      if (!config.headers) {
        config.headers = new axios.AxiosHeaders();
      }
      if (config.interceptors?.request) {
        config = config.interceptors.request(config);
      }

      this.instance
        .request(config)
        .then((res) => {
          // 单个响应的拦截器
          if (config.interceptors?.response) {
            res = config.interceptors.response(res);
          }
          resolve(res);
        })
        .catch((err) => {
          // 单个响应异常的拦截器
          if (config.interceptors?.responseCatch) {
            err = config.interceptors.responseCatch(err);
          }

          reject(err);
        });
    });
  }

  /** get请求 */
  get(url, data) {
    return this.request({
      url,
      method: "GET",
      params: data,
    });
  }
  /** post请求，body为form表单 */
  postForm(url, data) {
    return this.request({
      url,
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      data,
    });
  }
  /** post请求，body为json */
  post(url, data) {
    return this.request({
      url,
      method: "POST",
      data,
    });
  }
}

const errorHandle = (status, other) => {
  switch (status) {
    case 400:
      console.log("信息校验失败");
      break;
    case 401:
      console.log("认证失败");
      break;
    case 403:
      console.log("token校验失败");
      break;
    case 404:
      console.log("请求的资源不存在");
      break;
    default:
      console.log(other);
      break;
  }
};

module.exports = Request;
